<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.blurry"
          clearable
          size="small"
          placeholder="输入文章名称搜索"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <date-range-picker v-model="query.createTime" class="date-item" unlink-panels />
        <el-select
          v-model="query.enabled"
          clearable
          size="small"
          placeholder="状态"
          class="filter-item"
          style="width: 90px"
          @change="crud.toQuery"
        >
          <el-option v-for="item in enabledTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
        <rrOperation />
        <treeselect
          v-model="query.deptId"
          :options="depts"
          :load-options="loadDepts"
          style="width: 150px; "
          placeholder="选择栏目"
          @input="searchChange"
          @select="searchChange"
        />
      </div>
      <crudOperation :permission="permission">
        <template slot="right">
          <el-button
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-upload"
            @click="manageKeywords"
          >关键词管理
          </el-button>
        </template>
      </crudOperation>
    </div>

    <el-dialog append-to-body :visible.sync="keywordDialog" :title="'关键词管理'" width="900px">
      <div>
        <div style="height: 450px;">
          <el-table ref="singleTable" height="400" :data="keywordData" border highlight-current-row style="width: 100%; " @current-change="handleCurrentChange">
            <el-table-column prop="keyword" label="关键词" />
            <el-table-column prop="value" label="值" />
            <el-table-column prop="createTime" width="150" label="创建时间" />
            <el-table-column
              label="操作"
              width="100"
              align="center"
              fixed="right"
            >
              <template slot-scope="scope">
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteKeyword(scope.row.id)" />
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :page-size.sync="page.size"
            :total="page.total"
            :current-page.sync="page.page"
            style="margin-top: 8px;"
            layout="total, prev, pager, next, sizes"
            @current-change="changePage"
          />
        </div>
        <div style="display:flex; flex-direction: row; align-items:center;height: 100px;">
          <el-form ref="keywordForm" :model="keywordForm" :rules="keywordRules" style="margin-top: 15px;" size="small" label-width="100px">
            <el-form-item label="关键词" prop="keyword">
              <el-input v-model="keywordForm.keyword" style="width: 400px" placeholder="请输入关键词名" />
            </el-form-item>
            <el-form-item label="链接" prop="value">
              <el-input v-model="keywordForm.value" style="width: 400px" placeholder="请输入链接" />
            </el-form-item>
          </el-form>
          <div><el-button :loading="saveKeywordLoading" style="margin-top: 40px;margin-left: 5px;" type="info" @click="clearKeyword">清除选择</el-button>
            <el-button :loading="saveKeywordLoading" style="margin-top: 40px;margin-left: 5px;" type="primary" @click="saveKeyword">保存</el-button></div>
        </div>
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      lazy
      :load="getArticleDatas"
      :data="crud.data"
      row-key="id"
      @select="crud.selectChange"
      @select-all="crud.selectAllChange"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="名称" prop="articleName">
        <template slot-scope="scope">
          <div>
            <el-badge v-if="scope.row.isTop" value="置顶" class="item"><a
              :href="'/share-article?id=' + scope.row.id+'&pid='+$store.state.user.user.id"
              target="_blank"
              style="color: #3A71A8"
              v-text="scope.row.articleName"
            /></el-badge>
            <a
              v-else
              :href="'/share-article?id=' + scope.row.id+'&pid='+$store.state.user.user.id"
              target="_blank"
              style="color: #3A71A8"
              v-text="scope.row.articleName"
            />
            <el-button type="text" size="mini" icon="el-icon-document-copy" @click="copyToClipBoard(scope.row.id)" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="栏目" property="dept">
        <template slot-scope="scope">
          <div>
            <span
              v-text="scope.row.dept.name"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center" prop="enabled">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enabled"
            active-color="#409EFF"
            inactive-color="#F56C6C"
            @change="changeEnabled(scope.row, scope.row.enabled,)"
          />
        </template>
      </el-table-column>
      <el-table-column label="置顶" width="100" align="center" prop="isTop">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isTop"
            active-color="#409EFF"
            inactive-color="#F56C6C"
            @change="changeTop(scope.row, scope.row.isTop)"
          />
        </template>
      </el-table-column>
      <el-table-column label="价格" width="130" align="center" prop="price">
        <template slot-scope="scope">
          <div>
            <span v-if="scope.row.price > 0">{{ scope.row.price }}元<span v-if="scope.row.vipFree" style="color: red;">(VIP免费)</span></span>
            <span
              v-else
            >免费</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="buyCount" width="100" label="购买人数">
        <template slot-scope="scope">
          <a style="color: #00a0e9;" @click="getBuyDetail(scope.row.id)">{{ scope.row.buyCount }}</a>
        </template>
      </el-table-column>
      <el-table-column prop="readCount" width="100" label="阅读次数" />
      <el-table-column prop="createTime" label="创建日期" />
      <el-table-column prop="lastUpdateTime" label="更新日期" />
      <el-table-column prop="author" label="作者">
        <template slot-scope="scope">
          <span>{{ scope.row.author.username }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="checkPer(['admin','dept:edit','dept:del'])"
        label="操作"
        width="130px"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <udOperation
            :data="scope.row"
            :permission="permission"
            msg="确定删除吗，此操作不能撤销！"
          />
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
  </div>
</template>

<script>
import crudArticle from '@/api/system/article'
import crudKeyword from '@/api/system/keyword'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import CRUD, { crud, form, header, presenter } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import DateRangePicker from '@/components/DateRangePicker'
import pagination from '@crud/Pagination'
import Treeselect, { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getDepts, getDeptSuperior } from '../../../api/system/dept'
import { mapGetters } from 'vuex'
const defaultForm = { id: null, name: null, isTop: '1', subCount: 0, pid: null, deptSort: 999, enabled: 'true' }
export default {
  name: 'Article',
  components: { crudOperation, rrOperation, udOperation, DateRangePicker, pagination, Treeselect },
  cruds() {
    return CRUD({ title: '文章', url: 'api/article', sort: ['id,desc'], crudMethod: { ...crudArticle }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  // 设置数据字典
  dicts: ['article_status', 'article_type', 'top_status'],
  data() {
    return {
      page: {
        size: 10,
        total: 0,
        page: 1
      },
      depts: [],
      keywordDialog: false,
      keywordForm: { keyword: '', value: '' },
      keywordData: [],
      keywordRules: {
        keyword: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        value: [
          { required: true, message: '请输入链接', trigger: 'blur' }
        ]
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        deptSort: [
          { required: true, message: '请输入序号', trigger: 'blur', type: 'number' }
        ]
      },
      saveKeywordLoading: false,
      permission: {
        add: ['admin', 'dept:add'],
        edit: ['admin', 'dept:edit'],
        del: ['admin', 'dept:del']
      },
      enabledTypeOptions: [
        { key: 'true', display_name: '正常' },
        { key: 'false', display_name: '禁用' }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  mounted() {
    this.getDepts()
  },
  methods: {
    changePage(event) {
      this.page.page = event
      this.loadKeywords()
    },
    changeSize(event) {
      this.page.page = 1
      this.page.size = event
      this.loadKeywords()
    },
    handleCurrentChange(val) {
      if (val) {
        // 保存当前的角色id
        if (this.keywordForm === val) {
          this.$refs.singleTable.setCurrentRow()
        } else {
          this.keywordForm = val
        }
      } else {
        this.keywordForm = { keyword: '', value: '' }
      }
    },
    getBuyDetail(id) {
      this.$router.push('/system/purchase?articleId=' + id + '&type=0&state=3')
    },
    copyToClipBoard(id) {
      navigator.clipboard.writeText(this.baseApi + 'share-article?id=' + id)
        .then(() => {
          this.$message.success('文章链接已复制到剪切板')
        })
    },
    getArticleDatas(tree, treeNode, resolve) {
      const params = { pid: tree.id }
      setTimeout(() => {
        crudArticle.getArticles(params).then(res => {
          resolve(res.content)
        })
      }, 100)
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      form.enabled = `${form.enabled}`
    },
    deptSelect() {

    },
    searchChange(searchQuery, instanceId) {
      setTimeout(() => {
        this.crud.refresh()
      }, 300)
    },
    clearKeyword() {
      this.$refs.singleTable.setCurrentRow()
    },
    saveKeyword() {
      if (this.keywordForm.id) {
        crudKeyword.edit(this.keywordForm).then(() => {
          this.loadKeywords()
          this.$message.success('保存成功')
        })
      } else {
        crudKeyword.add(this.keywordForm).then(() => {
          this.page.page = 1
          this.loadKeywords()
          this.$message.success('保存成功')
        })
      }
    },
    deleteKeyword(id) {
      crudKeyword.del([id]).then(() => {
        if (this.keywordData.length === 1 && this.page.page !== 0) {
          this.page.page = this.page.page - 1
        }
        this.loadKeywords()
      })
    },
    manageKeywords() {
      this.keywordDialog = true
      this.loadKeywords()
    },
    loadKeywords() {
      crudKeyword.getKeywords({ page: this.page.page - 1, size: this.page.size, sort: 'createTime,desc' }).then(data => {
        console.log(data)
        this.keywordData = data.content
        this.page.total = data.totalElements
      })
    },
    getDepts(callback) {
      getDepts({ pidIsNull: true }).then(res => {
        this.depts = res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
        callback && callback()
      })
    },
    getSupDepts(deptId) {
      getDeptSuperior(deptId).then(res => {
        const date = res.content
        this.buildDepts(date)
        this.depts = date
      })
    },
    buildDepts(depts) {
      depts.forEach(data => {
        if (data.children) {
          this.buildDepts(data.children)
        }
        if (data.hasChildren && !data.children) {
          data.children = null
        }
      })
    },
    // 获取弹窗内部门数据
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ pid: parentNode.id }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },
    // 新增编辑前做的操作
    [CRUD.HOOK.beforeToCU](crud, form) {
      if (form.id) {
        this.$router.push('/article/detail?id=' + form.id)
      } else {
        this.$router.push('/article/detail')
      }
    },
    // 改变状态
    changeEnabled(data, val) {
      this.$confirm('此操作将 "' + this.dict.label.article_status[val] + '" ' + data.articleName + '文章, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudArticle.edit(data).then(res => {
          this.crud.notify(this.dict.label.article_status[val] + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(err => {
          data.enabled = !data.enabled
          console.log(err.response.data.message)
        })
      }).catch(() => {
        data.enabled = !data.enabled
      })
    },
    // 改变状态
    changeTop(data, val) {
      this.$confirm('此操作将 "' + this.dict.label.top_status[val] + '" ' + data.articleName + '文章, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudArticle.edit(data).then(res => {
          this.crud.notify(this.dict.label.top_status[val] + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(err => {
          data.isTop = !data.isTop
          console.log(err.response.data.message)
        })
      }).catch(() => {
        data.isTop = !data.isTop
      })
    }

  },
  beforeRouteEnter(to, from, next) {
    next(vm => vm.crud.refresh())
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .vue-treeselect__control, ::v-deep .vue-treeselect__placeholder, ::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
.item {
  margin-top: 10px;
  margin-right: 40px;
}
</style>
